<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>家族管理系统 - 控制台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand" href="/dashboard">家族管理系统</a>
        <div class="collapse navbar-collapse">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link active" href="dashboard">控制台</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/members">成员管理</a>
                </li>
            </ul>
            <form th:action="@{/logout}" method="post">
                <button type="submit" class="btn btn-outline-light">退出</button>
            </form>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>欢迎回来, <span th:text="${#authentication.name}"></span></h4>
                </div>
                <div class="card-body">
                    <p>这里是您的家族管理控制台。</p>
                    <a href="/admin/members" class="btn btn-primary">管理家族成员</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card-body">
    <div class="d-flex justify-content-between mb-3">
        <p class="mb-0">家族关系图谱</p>
        <button id="refreshGraph" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-clockwise"></i> 刷新
        </button>
    </div>
    <div id="familyGraph" style="height: 600px; border: 1px solid #ddd; border-radius: 5px;"></div>
    <div id="tooltip" class="position-fixed bg-light p-2 rounded shadow" style="display: none;"></div>
    <a href="/admin/members" class="btn btn-primary mt-3">管理家族成员</a>
</div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<style>
    .node circle {
        fill: #fff;
        stroke: steelblue;
        stroke-width: 2px;
    }

    .node text {
        font: 12px sans-serif;
    }

    .link {
        fill: none;
        stroke-width: 2px;
    }

    /* 不同关系类型的样式 */
    .link.父子 {
        stroke: #1f77b4;
        stroke-dasharray: 5, 5;
    }

    /* 不同关系类型的样式 */
    .link.父女 {
        stroke: #dc3545;
        stroke-dasharray: 5, 5;
    }

    .link.夫妻 {
        stroke: #ff7f0e;
    }

    .link.母子 {
        stroke: #2ca02c;
        stroke-dasharray: 2, 4;
    }

    .link.兄弟 {
        stroke: #d62728;
    }

    .relation-label {
        font-size: 10px;
        fill: #333;
        text-anchor: middle;
        pointer-events: none;
    }

    .node-name {
        font-size: 12px;
        text-anchor: middle;
        font-weight: bold;
    }

    #tooltip {
        z-index: 1000;
        max-width: 200px;
    }
</style>
<script th:inline="javascript">
    /*<![CDATA[*/
    // 1. 获取数据
    function loadFamilyData() {
        fetch('/api/family/graph')
            .then(response => response.json())
            .then(data => renderGraph(data));
    }

    // 2. 渲染图谱
    function renderGraph(data) {
        const container = document.getElementById('familyGraph');
        container.innerHTML = '';

        const width = container.clientWidth;
        const height = 600;

        // 1. 创建节点映射
        const nodeMap = new Map(data.members.map(m => [m.id, m]));

        // 2. 转换关系数据
        const links = data.relations
            .map(rel => {
                const source = nodeMap.get(rel.fromMemberId);
                const target = nodeMap.get(rel.toMemberId);
                return source && target ? {
                    source: source,
                    target: target,
                    type: rel.relationType,
                    description: rel.relationDescription,
                    ...rel
                } : null;
            })
            .filter(Boolean);

        // 3. 创建SVG和力导向图
        const svg = d3.select('#familyGraph')
            .append('svg')
            .attr('width', width)
            .attr('height', height);

        const simulation = d3.forceSimulation(data.members)
            .force('link', d3.forceLink(links).id(d => d.id).distance(120))
            .force('charge', d3.forceManyBody().strength(-200))
            .force('center', d3.forceCenter(width / 2, height / 2))
            .force('collision', d3.forceCollide().radius(40));

        // 4. 绘制连线
        const link = svg.append('g')
            .selectAll('line')
            .data(links)
            .enter()
            .append('line')
            .attr('class', d => 'link ' + d.type)
            .attr('data-description', d => d.description)
            .on('mouseover', function (event, d) {
                const tooltip = document.getElementById('tooltip');
                tooltip.style.display = 'block';
                tooltip.style.left = (event.pageX + 10) + 'px';
                tooltip.style.top = (event.pageY + 10) + 'px';
                tooltip.innerHTML = `<strong>${d.type}</strong><br>${d.description}`;
            })
            .on('mouseout', function () {
                document.getElementById('tooltip').style.display = 'none';
            });

        // 添加关系标签
        const linkLabels = svg.append('g')
            .selectAll('text')
            .data(links)
            .enter()
            .append('text')
            .attr('class', 'relation-label')
            .text(d => d.type);

        // 5. 绘制节点
        const node = svg.append('g')
            .selectAll('g')
            .data(data.members)
            .enter()
            .append('g')
            .call(d3.drag()
                .on('start', dragstarted)
                .on('drag', dragged)
                .on('end', dragended));

        // 添加头像定义 - 修复版
        const defs = svg.append('defs');
        data.members.forEach(d => {
            if (d.avatarUrl) {
                defs.append('pattern')
                    .attr('id', 'avatar-' + d.id)
                    .attr('width', 60)
                    .attr('height', 60)
                    .attr('patternUnits', 'userSpaceOnUse')
                    .append('image')
                    .attr('xlink:href', d.avatarUrl)
                    .attr('width', 60)
                    .attr('height', 60)
                    .attr('x', 0)
                    .attr('y', 0);
            }
        });

        // 头像或默认圆形
        node.append('circle')
            .attr('r', 30)
            .attr('fill', d => {
                if (!d.avatarUrl) return '#69b3a2';

                // 检查头像URL是否有效
                const img = new Image();
                img.src = d.avatarUrl.startsWith('http') ? d.avatarUrl : '/images/default-avatar.jpg';
                img.onerror = () => {
                    console.error(`头像加载失败: ${d.avatarUrl}`);
                    d3.select(this).attr('fill', '#69b3a2');
                };

                return `url(#avatar-${d.id})`;
            })
            .on('mouseover', function(event, d) {
                const tooltip = document.getElementById('tooltip');
                tooltip.style.display = 'block';
                tooltip.style.left = (event.pageX + 10) + 'px';
                tooltip.style.top = (event.pageY + 10) + 'px';
                tooltip.innerHTML = `<strong>${d.name}</strong><br>${d.personalDescription || '暂无描述'}`;
            })
            .on('mouseout', function() {
                document.getElementById('tooltip').style.display = 'none';
            });


        // 添加姓名标签
        node.append('text')
            .attr('class', 'node-name')
            .attr('dy', 40)
            .text(d => d.name);

        // 更新位置
        simulation.on('tick', () => {
            link
                .attr('x1', d => d.source.x)
                .attr('y1', d => d.source.y)
                .attr('x2', d => d.target.x)
                .attr('y2', d => d.target.y);

            linkLabels
                .attr('x', d => (d.source.x + d.target.x) / 2)
                .attr('y', d => (d.source.y + d.target.y) / 2);

            node.attr('transform', d => `translate(${d.x},${d.y})`);
        });

        function dragstarted(event, d) {
            if (!event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(event, d) {
            d.fx = event.x;
            d.fy = event.y;
        }

        function dragended(event, d) {
            if (!event.active) simulation.alphaTarget(0);
            d.fx = null;
            d.fy = null;
        }
    }

    // 3. 初始加载
    document.addEventListener('DOMContentLoaded', loadFamilyData);
    document.getElementById('refreshGraph').addEventListener('click', loadFamilyData);
    /*]]>*/
</script>
</body>
</html>